<template>
  <div class="timeingTask" id="timeingTask">
    <!-- 功能按钮 -->
    <div class="timeingTask_button">
      <a-button class="addButton" type="primary" @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>

      <div class="searchContent">
        <a-input v-model:value="tagName" placeholder="搜索任务名称" style="width: 192px">
          <template #suffix>
            <i class="iconfont icon-search" @click="onSearch"></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable
      :columns="columns.timeingTaskColumns"
      :dataSource="configData.records"
      :isSelect="true"
      :scroll="scroll"
      ref="tagBaseTables"
      :isShowPagination="isShowPagination"
      :showCheckDelete="showCheckDelete"
      :total="configData.total"
      @changePage="changePage"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" @click="eidtRecord(record)">{{ record.oparation[0] }}</a>
          <a-popconfirm
            placement="topRight"
            ok-text="Yes"
            cancel-text="No"
            @confirm="confirmDelete(record)"
          >
            <template #title>
              <p style="width: 197px">删除此tag词后，内容处也同时删除</p>
            </template>
            <a>{{ record.oparation[1] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="deleteSelectedAll"
          :disabled="!rowSelection.length"
          >删除</a-button
        ></template
      >
    </baseTable>
    <!-- 新建tag词模态框 -->
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      @handleOk="buttonMessage"
      @handleCancle="isVisible = false"
      class="tagword_modal"
    >
      <template v-slot:body>
        <a-form
          name="advanced_search"
          class="ant-advanced-search-form"
          autoComplete="off"
          :model="formState"
          ref="sensitiveFrom"
        >
          <a-form-item
            class="tag-item"
            :name="['timeingTask', 'value']"
            :label="formState.timeingTask.label"
            :rules="[formState.timeingTask.rule]"
          >
            <a-input
              v-model:value="formState.timeingTask.value"
              show-count
              :maxlength="25"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
//data
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let tagName = ref<string>("");
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const tagBaseTables = ref<any>(null); // basetable的ref
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);

// 模态框数据
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建tag词",
});
const sensitiveFrom = ref<any>("sensitiveFrom");

const formState = reactive<dataSourceType>({
  timeingTask: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "tag词不可为空！",
    },
    label: "tag词汇",
  },
  id: "",
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
// computed
rowSelection = computed(() => {
  return tagBaseTables.value.selectedRowKeys;
});
//methods
const addRecord = async () => {
  //新加tag词模态框条件修改
  //添加tag词数据
  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建tag词";
  formState.timeingTask.value = "";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const eidtRecord = async (item: dataSourceType) => {
  //编辑tag词数据
  isAddOrEdit.value = true;
  modAlProps.title = "编辑tag词";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  formState.timeingTask.value = item.tagName;
  formState.id = item.id;
  isVisible.value = true;
};

const buttonMessage = async (msg: dataSourceType) => {
  // 新添或编辑tag词调取接口
  //保存
  sensitiveFrom.value
    .validate()
    .then(() => {
      let params: dataSourceType = {
        tagName: formState.timeingTask.value,
        id: formState.id,
      };
      let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";

      request[type === "Edit" ? "fetchContentTagUpdate" : "fetchContentTag"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRecord();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });

      isVisible.value = msg.text == "保存" ? false : true;
    })
    .catch(() => {});
};

const confirmDelete = async (item: any) => {
  // 删除单个tag词
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

const deleteSelectedAll = async () => {
  //删除已选所有tag词
  let keys: (string | number)[] = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定删除选中的tag词？删除后无法恢复",
      content: "删除tag词后，内容处也同时删除",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
        
      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除tag词
  await request.fetchContentTagDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRecord({});
    } else {
      message.error(res.message);
    }
  });
};
const onSearch = async () => {
  //搜索获取数据参数配置
  let datas: dataSourceType = {
    tagName: tagName.value,
  };
  getRecord(datas);
};
const getRecord = async (datas: dataSourceType = {}) => {
  // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    tagName: datas.tagName || "",
  };
  const telData = (await request.fetchContentTagPage(data)) || {};
  let reqData = telData;
  let sourceData = ref<dataSourceType[]>([]);
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      ...item.middleDto,
      refCounter: item.refCounter,
      oparation: ["编辑", "删除"],
      num: index + 1,
      tagName: item.tagName,
      createTime: item.createTime,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  tagBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    scroll.y = getTableScroll(74, "timeingTask").y;
    scroll.isFixed = getTableScroll(74, "timeingTask").isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  getRecord(datas);
};

//onmounted
onMounted(() => {
  getRecord();
});
</script>
<style lang="scss" scoped>
.timeingTask {
  width: 100%;
  height: calc(100% - 88px);
  padding: 24px;
  background-color: #fff;
  overflow: hidden;

  .timeingTask_button {
    padding-bottom: 24px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

.tag-item {
  margin-bottom: 0 !important;
}

:deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 514px;
  margin-left: 4px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}
</style>
